package io.openkunlun.javadsl;

import io.grpc.Server;
import io.grpc.ServerBuilder;
import io.openkunlun.javadsl.client.DaprClient;
import io.openkunlun.javadsl.client.GetBulkStateAction;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;

public class DaprServer {

    private Server server;

    public static void main(String[] args) throws Exception {
        final DaprServer server = new DaprServer();
        server.start();
//        server.blockUntilShutdown();

        DaprClient daprClient = new DaprClient("172.16.1.55", 12345, 30000, 16 * 1024 * 1024, 8 * 1024);
        GetBulkStateAction action = GetBulkStateAction.builder()
                .storeName("123")
                .keys(new ArrayList<>())
                .metadata(new HashMap<>())
                .parallelism(0)
                .build();
        action.invoke(daprClient);
    }

    private void start() throws IOException {
        int port = 50051;
        server = ServerBuilder
                .forPort(port)
//                .addService(new InvocationHandler())
                .build()
                .start();
        Runtime.getRuntime().addShutdownHook(new Thread() {
            @Override
            public void run() {
                System.err.println("shutting down gRPC server since JVM is shutting down");
                try {
                    DaprServer.this.stop();
                } catch (InterruptedException e) {
                    e.printStackTrace(System.err);
                }
            }
        });
    }

    private void stop() throws InterruptedException {
        if (server != null) {
            server.shutdown().awaitTermination(30, TimeUnit.SECONDS);
        }
    }

    private void blockUntilShutdown() throws InterruptedException {
        if (server != null) {
            server.awaitTermination();
        }
    }
}
